package com.yy.satokenapplication.config;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.util.ObjectUtil;
import com.yy.satokenapplication.entity.SysPermission;
import com.yy.satokenapplication.entity.SysRole;
import com.yy.satokenapplication.entity.SysUser;
import com.yy.satokenapplication.mapper.SysUserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;

import java.util.Collections;
import java.util.List;

@Slf4j
public class SaPermissionImpl implements StpInterface {

    @Resource
    private SysUserMapper sysUserMapper;
    

    private SysUser getUserInfo(Long userId) {
        SysUser user = sysUserMapper.findUserWithRolesAndPermissionsById(userId);
        if (ObjectUtil.isEmpty(user)) {
            log.error("用户信息为空，无法获取用户信息！");
        }
        return user;
    }

    /**
     * 获取菜单权限列表
     */
    @Override
    @Cacheable(value = "permissions", key = "#loginId")
    public List<String> getPermissionList(Object loginId, String s) {
        SysUser userInfo = getUserInfo(Long.parseLong(loginId.toString()));
        if (ObjectUtil.isEmpty(userInfo)) {
            log.error("用户的菜单权限为空，无法获取菜单权限列表，用户登录ID: {}", loginId);
            return Collections.emptyList();
        }
        return userInfo.getPermissionsList().stream().map(SysPermission::getCode).toList();
    }

    /**
     * 获取角色权限列表
     */
    @Override
    @Cacheable(value = "roles", key = "#loginId")
    public List<String> getRoleList(Object loginId, String s) {
        Long userId = Long.parseLong(loginId.toString());
        SysUser userInfo = getUserInfo(userId);
        if (ObjectUtil.isEmpty(userInfo)) {
            log.error("用户角色信息为空，无法获取角色列表，用户ID: {}", userId);
            return Collections.emptyList(); // 返回空列表
        }
        return userInfo.getRolesList().stream().map(SysRole::getRoleCode).toList();
    }
    
}
